package io.terminus.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;
import io.terminus.spzx.common.config.exception.SpzxCustomException;
import io.terminus.spzx.manager.listener.EasyExcelListener;
import io.terminus.spzx.manager.mapper.CategoryMapper;
import io.terminus.spzx.manager.service.CategoryService;
import io.terminus.spzx.model.entity.product.Category;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 分类管理Service接口实现类
 * @Date 2024-09-21
 */
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> listCategory(Long id) {
        // 1、根据id查询list集合: SELECT * FROM category WHERE parent_id=#{id}
        List<Category> categoryList = categoryMapper.selectCategoryByParentId(id);

        //2、遍历返回list集合
        // 判断每个分类是否有下一层分类，如果有设置hasChildren = true
        if (CollectionUtils.isNotEmpty(categoryList)) {
            categoryList.forEach(category -> {
                // 判断每个分类是否有下一层分类: SELECT count(*) FROM category WHERE parent_id=#{category.id}
                int count = categoryMapper.selectCountByParentId(category.getId());
                // 下一层分类
                category.setHasChildren(count > 0);
            });
        }
        return categoryList;
    }

    @Override
    public List<Category> listParentCategory(Long id) {
        Category thirdCategory = categoryMapper.findById(id);
        Category secondCategory = categoryMapper.findById(thirdCategory.getParentId());
        Category firstCategory = categoryMapper.findById(secondCategory.getParentId());

        return Lists.newArrayList(firstCategory, secondCategory, thirdCategory);
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 1、设置响应头等信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            // 防止中文乱码, 和Easy Excel没关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            // 设置Content-disposition响应头
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 2、查询所有分类，返回list集合
            List<Category> categoryList = categoryMapper.findAll();

            // Category List -> Category Excel Vo List
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }

            // 3、调用Easy Excel的write方法完成写操作
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public void importData(MultipartFile file) {
        // Easy Excel监听器
        EasyExcelListener<CategoryExcelVo> excelListener = new EasyExcelListener<>(categoryMapper);
        try {
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, excelListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
